"""skytank_image.py Imagining for the SkyTanx robotics platform

This program contains functions for receiving and interpreting incoming video data on SkyTanX

"""

__author__ = "Leo Szeto"
__verion__ = "$Revision: 0.1 $"
__date__ = "$Date: 2011/05/09 $"
__copyright__ = "Copyright (c) 2011 Leo Szeto"
__license__ = "Python"

#Uses gtk to capture screenshots
import imagecap     #imagecap module by Michael Sechooler

import time	    #Mainly for reporting features

#PIL Libraries used for image processing
from PIL import Image
from PIL import ImageChops
from PIL import ImageEnhance
from PIL import ImageDraw
from PIL import ImageFilter

#Initializes the screen capture system, receive handler
def image_init(w, h, x, y):
	return imagecap.ImageCap(w, h, x, y)

def translate_to_PIL(string, length, width):
	im = Image.frombuffer("RGB", (length, width), string, 'raw', "RGB", 0, 1)	
	return im	

def downsample(im, size_x, size_y):
	im = im.resize((size_x, size_y))
	return im

#Creates an image of a solid color that is RGB
def create_color_image(length, width, red, green, blue):
	im = Image.new("RGB", (length, width), (red, green, blue))
	return im

#outputs a tuple using a couple calculations of bbox
def get_bbox_stats(im):
	bbox = im.getbbox()
	if bbox:
		box_w = (bbox[0] + bbox[2])/2
		box_h = (bbox[1] + bbox[3])/2
		area_x = abs(bbox[0] - bbox[2])
		area_y = abs(bbox[1] - bbox[3])
		Area = area_x*area_y
		#Returns the hotspot (0,1) and the area (2)
		return (box_w, box_h, Area)
	else:
		return -1;

#Takes an original image and filter it. Not meant to be used generically
#im: The original captured image
#sub: The color to subtract by. Determines which color to detect.
#max_heat: determines the tolerance of the filter. Black for things NOT sub
#size: The filter's minimum size for recognizing an object as an object
def filter_module(im, sub, max_heat, min_size, image_size, scale):
	im = ImageChops.difference(sub, im) 							#Subtract 
	im = im.convert("L")											#Greyscale
	im = Image.eval(im, lambda x: 255 if x < max_heat else 0)		#Set into a binary image
	im = downsample(im, image_size[0]*scale, image_size[1]*scale)   #Downsample to get better performance!
	im = im.filter(ImageFilter.MinFilter(min_size)) 	     		#Takes up the most time!
	return im

#Example
#window = image_init()
#pb = grab_image(window, 60, 80, 300, 300)
#im = translate_to_PIL(pb, 300, 300)
#red = create_color_image(300, 300, 255, 0, 0)
#out = filter_module(im, red, 70, 9)
#stat = get_bbox_stats(out)
#out.show()
#print stat
